module page {
    export class ExtPage extends egret.DisplayObjectContainer {
        public static readonly INIT_GAME: string = "init_game";
        private readonly scrollView = new egret.ScrollView();
        private usualLevel = new egret.DisplayObjectContainer();
        private topLevel = new egret.DisplayObjectContainer();
        private tableUI: egret.DisplayObjectContainer;
        private boxBg = new egret.DisplayObjectContainer();
        private boxImgs = [];
        private noticeAd = new egret.DisplayObjectContainer();
        private gameBg: egret.Bitmap = new egret.Bitmap();
        public needBox: boolean = false;
        private stagewidth: number = 750;
        private stageheight: number = 1624;
        private scale: number = 1;
        public static listData: any;
        public static auditData: any;
        private agent = 0;
        private msk: any;
        private notice_index = 0;
        private jump_mask_page;
        private page = 0;
        private count = 10;
        private stageW = 0;
        private stageH = 0;
        private first_list = [];
        public constructor(stagewidth: number, stageheight: number) {
            super();
            this.boxBg.visible = false;
            this.addChild(this.usualLevel);
            this.addChild(this.topLevel);
            this.scale = stagewidth / this.stagewidth;
            this.scaleX = this.scaleY = this.scale;
            // this.stagewidth = stagewidth;
            // this.stageheight = stageheight;
            var shp:egret.Shape = new egret.Shape();
            shp.graphics.beginFill( 0xffffff, 1);
            shp.graphics.drawRect( 0, 0, this.stagewidth, this.stageheight );
            console.log(this.stagewidth, this.stageheight);
            shp.graphics.endFill();
            this.usualLevel.addChild( shp );
            this.setAudit();
            setTimeout(this.checkJump.bind(this), 500);
        }

        private setAudit(): void {
            let data = manager.GameManager.auditData;
            ExtPage.auditData = data;
            if ((data["set"]["gdt_audit"] == "0") && (data["data"] != "3003")) {
                var imgLoader = new egret.ImageLoader();
                imgLoader.addEventListener(egret.Event.COMPLETE, function(ev) {
                    let imageLoader = ev.currentTarget;
                    this.msk = new egret.Texture();
                    this.msk._setBitmapData(imageLoader.data);
                    if (data["set"]["gdt_ad"] == "1") {
                        //广点通
                        this.showGdtAd();
                        this.needBox = true;
                        this.loadAppList();
                        let that = this;
                        wx.onHide(function(){
                            console.log("onHide: ", Main.getInstance().extPage.needBox);
                            if (Main.getInstance().extPage.needBox){
                                Main.getInstance().extPage.needBox = false;
                                that.showBox();
                                manager.GameManager.getInstance().statisticManager.getListStorage(that.first_list);
                                manager.GameManager.getInstance().statisticManager.adStats(null, "notice");
                            }
                        });
                    } else {
                        //盒子
                        this.boxBg.visible = true;
                        this.loadAppList();
                        this.showBox();
                        manager.GameManager.getInstance().statisticManager.adStats(null, "notice");
                    }
                }.bind(this), this);
                imgLoader.load("http://wx.11babay.cn/uploads/l/lxnkub1478500252/d/8/b/b/5c130d86b7697.png_p2js");
            } else {
                //游戏初始化
                this.dispatchEvent(new egret.Event(ExtPage.INIT_GAME));
            }
            //如果入口参数里有appid，显示跳转图层
        }

        private checkJump() {
            let query = wx.getLaunchOptionsSync().query;
            let appList = manager.StatisticsManager.navigateToMiniProgramAppIdList;
            if (!query.appid) {
                return;
            }
            if (appList && query.img && !manager.StatisticsManager.checkAppList(query.appid)) {
                setTimeout(function(){
                    helper.Helper.previewImg(query.img);
                }, 500);
                manager.GameManager.getInstance().statisticManager.statusPv(query.appid, query.path, 0, true);
                return;
            }
            this.jump_mask_page = new egret.DisplayObjectContainer();
            this.jump_mask_page.touchEnabled = true;
            this.jump_mask_page.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
                this.removeChild(this.topLevel);
                manager.GameManager.getInstance().statisticManager.statusPv(query.appid, query.path, 0, true);
                manager.StatisticsManager.goToMiniPro({appid: query.appid, path: query.path}, null);
            }, this);
            this.topLevel.addChild(this.jump_mask_page);
            var shp:egret.Shape = new egret.Shape();
            shp.graphics.beginFill( 0x000000, 0.6);
            shp.graphics.drawRect( 0, 0, this.stagewidth, this.stageheight );
            console.log(this.stagewidth, this.stageheight);
            shp.graphics.endFill();
            this.jump_mask_page.addChild( shp );
            var jump_img  = new egret.Bitmap();
            this.jump_mask_page.addChild( jump_img );
            jump_img.width = 600;
            jump_img.height = 857;
            jump_img.x = 75;
            jump_img.y = 240;
            var imgLoader = new egret.ImageLoader();
            imgLoader.addEventListener(egret.Event.COMPLETE, function(ev){
                let imageLoader = ev.currentTarget;
                let texture = new egret.Texture();
                texture._setBitmapData(imageLoader.data);
                jump_img.texture = texture;
            }, this);
            imgLoader.load("http://wx.11babay.cn/uploads/Q/Qdh4nAHglce5Bkn7PTKf/5/e/3/e/5bb02e7d3eacf.png");
        }

        private loadAppList() {
            let data = {
                token: manager.GameManager.getInstance().getAppToken(),
                count: 100,
                page: 0,
                agent: manager.GameManager.getInstance().getAgent()
            }
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open("https://2zhuji.cn/index.php?g=Wap&m=Wxa&a=get_user_app", egret.HttpMethod.GET);
            request.send(data);
            request.addEventListener(egret.Event.COMPLETE, this.setAppList, this);
        }

        private setAppList(event: egret.Event): void {
            console.log("setAppList");
            let request = <egret.HttpRequest>event.currentTarget;
            let datas = JSON.parse(request.response).data;
            ExtPage.listData = datas;
            if (!datas || !datas.length) return;
            let sys = wx.getSystemInfoSync();
            let sys_w = sys.screenWidth;
            let sys_h = sys.screenHeight;
            var w = this.stagewidth;
            var h = sys_h * (this.stagewidth / sys_w);
            this.stageW = w;
            this.stageH = h;

            this.boxBg.width = w;

            this.scrollView.setContent(this.boxBg);
            this.scrollView.touchEnabled = true;
            this.scrollView.addEventListener(egret.TouchEvent.TOUCH_END, function(){
                var sc = this.scrollView;
                if ((sc.scrollTop + sc.height) >= this.boxBg.height - 10) {
                    this.setList();
                }
            }, this);
            this.scrollView.x = 0;
            this.scrollView.y = 0;
            this.scrollView.verticalScrollPolicy = "on";
            this.scrollView.bounces = false;
            this.scrollView.width = w;
            this.scrollView.height = h;
            this.usualLevel.addChild(this.scrollView);

            this.tableUI = new egret.DisplayObjectContainer();
            this.boxBg.addChild(this.tableUI);
            this.tableUI.y = 0;
            this.tableUI.x = 0;
            this.tableUI.width = this.boxBg.width - this.tableUI.x * 2;
            this.tableUI.height = this.boxBg.height - this.tableUI.y;
            this.setList();
            this.showNoticeAd();
            console.log("setAppList end");
        }

        private setList(): void {
            let datas = ExtPage.listData;
            if (!datas || !datas.length || this.page == -1) return;
            let start = this.page * this.count;
            let end = Math.min(start + this.count, datas.length);
            if (start >= datas.length) {
                this.page = -1;
                return;
            }
            console.log("setList");
            let w = this.stageW;
            let h = this.stageH;

            let list = datas.slice();
            list = list.splice(start, end);

            if (this.boxBg.visible) {
                manager.GameManager.getInstance().statisticManager.getListStorage(list);
            } else {
                this.first_list = list.splice(start, end);
            }
           

            let col = 2;
            let space_x = 30;
            let space_y = 30;

            this.boxBg.height = Math.max(190 + (385 + space_y) * Math.ceil(end / col), h);
            this.tableUI.height = this.boxBg.height - this.tableUI.y;
            for (let i: number = start; i < end; i++) {
                var ctn = new egret.DisplayObjectContainer();
                ctn.width = 330;
                ctn.height = 380;
                ctn.touchEnabled = true;
                ctn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.goToBoxAd.bind(this, i), this);
                var img = new egret.Bitmap();
                img.width = ctn.width;
                img.height = 318;
                this.boxImgs[i] = img;
                ctn.addChild(img);
                var imgLoader = new egret.ImageLoader();
                imgLoader.addEventListener(egret.Event.COMPLETE, this.loadImg.bind(this, i), this);
                imgLoader.load(datas[i].wx_tlimg);
                var shp:egret.Shape = new egret.Shape();
                shp.graphics.beginFill( datas[i].color || this.getColor(i), 1);
                shp.graphics.drawRect( 0, 0, ctn.width, 62 );
                shp.y = 318;
                ctn.addChild(shp);
                var  name = datas[i].name || "";
                name = name.substring(0, 10);
                var label = this.getText(name, 32, 318 + 15);
                label.width = ctn.width;
                ctn.addChild(label);
                // var pv = (Number(datas[i].wxa_pv) + (Number(datas[i].default_pv) || 0) * 10000) || 0;
                // label = this.getText("在线人数" + pv, 23, 97);
                // ctn.addChild(label);
                var msk = new egret.Bitmap();
                msk.texture = this.msk;
                msk.width = ctn.width;
                msk.height = ctn.height;
                ctn.addChild(msk);
                ctn.x = space_x + (i % col) * (ctn.width + space_x);
                ctn.y = 190 + Math.floor(i / col) * (ctn.height + space_y);
                this.tableUI.addChild(ctn);
            }
            this.page ++;
        }

        private getColor(i) {
            i = i % 10;
            let colors = [0xad5fa0, 0x3f5774, 0x824e0f, 0x08388c, 0x0e6261, 0x654f78, 0xad5fa0, 0x3f5774, 0x824e0f, 0x08388c];
            return colors[i];
        }

        private showGdtAd(): void {
          var gdtad = ExtPage.auditData.gdtad && ExtPage.auditData.gdtad[0];
          if (gdtad && gdtad.appid && gdtad.img) {
            this.gameBg.width = this.stagewidth;
            this.gameBg.height = this.stageheight;
            this.usualLevel.addChild(this.gameBg);
            var bgImgUrl: string = gdtad.img;
            let imgLoader = new egret.ImageLoader();
            imgLoader.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                let imageLoader = <egret.ImageLoader>event.currentTarget;
                let texture = new egret.Texture();
                texture._setBitmapData(imageLoader.data);
                this.gameBg.$setTexture(texture);
                this.gameBg.touchEnabled = true;
                this.gameBg.addEventListener(egret.TouchEvent.TOUCH_TAP, this.goToGdt, this);
            }, this);
            imgLoader.load(bgImgUrl);
            manager.GameManager.getInstance().statisticManager.adStats(null, "gdt", gdtad);
          } else {
              console.log("广点通未配置");
          }
        }

        private showBox(): void {
            if (this.gameBg) {
                this.gameBg.visible = false;
            }
            this.boxBg.visible = true;
        }

        private goToGdt(): void {
            var gdtad = ExtPage.auditData.gdtad[0];
            this.showAd("gdt", gdtad);
        }

        private showNoticeAd () {
            let data = ExtPage.auditData;
            if (data && data.noticead && data.noticead.length) {
                this.notice_index = Math.floor(Math.random() * data.noticead.length);
                var noticead = data.noticead[this.notice_index];
                if (!noticead.img) return;
                this.boxBg.addChild(this.noticeAd);
                this.noticeAd.touchEnabled = true;
                var that = this;
                this.noticeAd.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
                    this.showAd("notice", noticead);
                    that.tableUI.y = that.tableUI.y - 94;
                    that.noticeAd.visible = false;
                }, this);
                this.noticeAd.x = 207;
                this.noticeAd.y = 65;
                let img = new egret.Bitmap();
                this.noticeAd.addChild(img);
                img.width = 64;
                img.height = 64;
                img.x = 10;
                img.y = 23;
                let imgLoader = new egret.ImageLoader;
                imgLoader.addEventListener(egret.Event.COMPLETE, function(ev){
                    let texture = new egret.Texture();
                    texture._setBitmapData(ev.currentTarget.data);
                    img.texture = texture;
                }, this);
                imgLoader.load(noticead.img)

                let bg = new egret.Bitmap();
                bg.width = 347;
                bg.height = 95;
                this.noticeAd.addChild(bg);
                let bgloader = new egret.ImageLoader;
                bgloader.load("http://wx.11babay.cn/uploads/p/pjNjl1htjHPnciglS6aC/a/8/d/0/5bd7efeaf01e4.png_p2js");
                bgloader.addEventListener(egret.Event.COMPLETE, function(ev){
                    let texture = new egret.Texture();
                    texture._setBitmapData(ev.currentTarget.data);
                    bg.texture = texture;
                }, this);
            }
        }

        private getText (text: string, size, y) {
            var label = new egret.TextField();
            label.textColor = 0xffffff;
            label.textAlign = "center";
            label.text = text;
            label.size = size;
            label.y = y;
            return label;
        }

        private loadImg (index, ev) {
            let imageLoader = ev.currentTarget;
            let texture = new egret.Texture();
            texture._setBitmapData(imageLoader.data);
            this.boxImgs[index].texture = texture;
        }
        
        private goToBoxAd (index) {
            let data = {
                appid: ExtPage.listData[index].appid,
                path: ExtPage.listData[index].path || ""
            }
            var app_id = ExtPage.listData[index].id;
            var list_id = ExtPage.listData[index].list_id;
            if (ExtPage.listData[index].category_id == "2484") {
                manager.GameManager.getInstance().statisticManager.statsAppPv(ExtPage.listData[index].id);
                manager.GameManager.getInstance().statisticManager.statsListClick(app_id);
                this.goToCustomer({session: ExtPage.listData[index].float_session});
            } else if (data.appid) {
                manager.GameManager.getInstance().statisticManager.statsListClick(app_id);
                manager.GameManager.getInstance().statisticManager.statsTunnelClickFrom(data.path, 'list', list_id, 0)
                manager.GameManager.getInstance().statisticManager.statusPv(data.appid, data.path, app_id);
                manager.StatisticsManager.goToMiniPro(data, null);
            }
        }

        private goToCustomer(ad): void {
            if (!ad.session) return;
            ad.session = manager.GameManager.getInstance().getSession(ad.session);
            wx.openCustomerServiceConversation({
                sessionFrom:ad.session,
                showMessageCard:ad.showMessageCard||false,
                sendMessageTitle:ad.sendMessageTitle||"",
                sendMessagePath:ad.sendMessagePath||"",
                sendMessageImg:ad.sendMessageImg||"",
                complete:res=>{
                    console.log("ad_list session "+ad.session+":",res);
                }
            });
        }

        public showAd(type:string, ad) {
            if(!ad){
                return;
            }
            let SDKVersion = wx.getSystemInfoSync().SDKVersion;
            manager.GameManager.getInstance().statisticManager.adStats(1, type, ad);
            if(ad.type == 2 && (helper.Helper.compareVersion(SDKVersion,'2.0.3') === 1)) {
                //客服
                let session = ad.session&&ad.session.indexOf("y1yad_")==0?ad.session:"y1yad_"+ad.session||"";
                wx.openCustomerServiceConversation({
                    sessionFrom:session,
                    showMessageCard:ad.showMessageCard||false,
                    sendMessageTitle:ad.sendMessageTitle||"",
                    sendMessagePath:ad.sendMessagePath||"",
                    sendMessageImg:ad.sendMessageImg||"",
                    complete:res=>{
                        console.log("ad "+type+" session "+ad.session+":",res);
                    }
                });
            } else if (ad.type == 1 && ad.appid && (helper.Helper.compareVersion(SDKVersion,'2.2.0') === 1)) {
                //进入其他小程序
                manager.StatisticsManager.goToMiniPro({appid: ad.appid, path: ad.path}, null);
                manager.GameManager.getInstance().statisticManager.statusPv(ad.appid, ad.path, 0);
            } else if (ad.ad_img) {
                helper.Helper.previewImg(ad.ad_img);
            }
        }
    }

}